/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Example_04_Enum_Serialization.java]
 * Creation Date        [09-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_09_io.serializaion;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * JDK 5之前的枚举定义, 只有一个常量值<br>
 * 默认的序列化机制不适于自定义枚举: 即使构造器私有, 序列化机制也能创建新的对象<br>
 * JDK 5的枚举则可以正常序列化
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Example_04_Enum_Serialization implements Serializable {

	private static final long serialVersionUID = -3379976694385644115L;

	private final int value;

	public static final Example_04_Enum_Serialization V = new Example_04_Enum_Serialization(
			1);

	private Example_04_Enum_Serialization(int value) {
		this.value = value;
	}

	public int getValue() {
		return value;
	}

	/**
	 * 错误的序列化方式
	 * 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static void incorrectSerializationMethod() throws IOException,
			ClassNotFoundException {
		Example_04_Enum_Serialization v1 = Example_04_Enum_Serialization.V;
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
				"enum1.ser"));
		out.writeObject(v1);
		out.close();

		ObjectInputStream in = new ObjectInputStream(new FileInputStream(
				"enum1.ser"));
		Example_04_Enum_Serialization v2 = (Example_04_Enum_Serialization) in
				.readObject();
		in.close();

		if (v1 == v2) {
			System.out.println("Serialization successfully");
		} else {
			System.out.println("serialization unsuccessfully");
		}
	}

	/**
	 * 正确的序列化方式 (单例模式也要使用此种序列化方式)
	 * 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static void correctSerializationMethod() throws IOException,
			ClassNotFoundException {
		Example_04_Enum_Serialization v1 = Example_04_Enum_Serialization.V;
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
				"enum2.ser"));
		out.writeInt(v1.getValue());
		out.close();

		ObjectInputStream in = new ObjectInputStream(new FileInputStream(
				"enum2.ser"));
		int v2 = in.readInt();
		in.close();

		if (v1.value == v2) {
			System.out.println("Serialization successfully");
		} else {
			System.out.println("serialization unsuccessfully");
		}

	}

	public static void main(String[] args) {
		try {
			incorrectSerializationMethod();
			correctSerializationMethod();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
